package Upload;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Date;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Log.LogManager;

public class FileRegister extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public FileRegister() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		try {
			ServletContext application=getServletContext();
			String username=request.getParameter("username");
			String caption=request.getParameter("caption");
			String path=request.getParameter("path");
			if(((String) application.getAttribute("systempi")).equals("\\")==true){
				path=path.replaceAll("[\\\\]","\\\\\\\\");
			}
			System.out.println(path);
			String sqls1="INSERT INTO file(caption,path,time,user) VALUES('"+caption+"','"+path+"','"+new Date()+"','"+username+"')";
			Connection con=(Connection) application.getAttribute("con");
			Statement sm=con.createStatement();
			int result=sm.executeUpdate(sqls1);
			response.setContentType("text/html; charset=utf-8");
			PrintWriter out = response.getWriter();
			if(result!=1){
				out.print("fail");
			}else{
				out.print("succes");
			}
			out.flush();
			out.close();
		} catch (Exception e) {
			LogManager.log(e.toString());
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
